/**
 * Created by zhouli on 18/6/25
 * Email li.zhou@huilianyi.com
 * 导出
 * 支持加密验证
 */
import React from 'react';
import {connect} from 'react-redux';
import {Modal, Button, Progress, Icon, Input, message, Select, Form} from 'antd';
import 'styles/components/template/export-modal/export-modal.scss';
import ExportService from 'components/template/export-modal/export-modal.service';
import {deepFullCopy, messages} from "share/common";

const InputGroup = Input.Group;
const Option = Select.Option;
let codeTimer = null;

class ExportModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isSended: false,//验证码是否有发送
      getCodeType: "mobile",
      token: "",//验证码
      _mobile: "",//手机加密
      _email: "",//邮箱加密
      timeNumber: 0,
      timer: null,
      visible: false,
      step: "pending",//error,success
      progressNum: 0,
      errorDetail: "",
      path: "",
      isCancel: false,
      codeCheckConfirming: false
    };
  }

  componentWillMount() {
  }
  //导出入口
  exportInfo = () => {
    //王若楠优化，取这部分--start
    const { exportType, exportCondition, exportCommand } = this.props;
    let timestamp = Date.parse(new Date());
    if(exportType === "REPORT"){
      let param = {
        exportType: exportCondition.exportType,
        command: exportCondition.command,
        timestamp: timestamp
      };
      let temp = deepFullCopy(exportCondition);
      temp.timestamp = timestamp;
      ExportService.exportInfoForReport(param, temp)
        .then((res) => {
          this.exportInfoProgressForReport(param);
        })
    }else{
      let param = {
        exportType: exportType,
        timestamp: timestamp,
        command: exportCommand || ''
      };
      ExportService.exportInfo(param, this.props.exportCondition)
        .then((res) => {
          this.exportInfoProgress(param);
        })
    }
    //王若楠优化，取这部分--end
  };

  exportInfoProgress = (param) => {
    ExportService.exportInfoProgress(param)
      .then((res) => {
        this.setState({
          progressNum: res.data && res.data.progress ? parseInt(res.data.progress) : 0,
          path: "",
        });
        if (res.data.status === "S") {
          clearInterval(this.state.timer);
          this.setState({
            step: "success",
            path: res.data.path
          }, () => {
            // this.downloadByPath(res.data.path)
          })

        } else if (res.data.status === "E") {
          clearInterval(this.state.timer);
          this.setState({
            step: "error",
            path: "",
            errorDetail: res.data.errorDetail
          })
        } else {
          clearInterval(this.state.timer);
          let that = this;
          this.state.timer = setInterval(function () {
            that.exportInfoProgress(param);
          }, 2000)
        }
      })
      .catch((err) => {
        clearInterval(this.state.timer);
        this.setState({
          step: "error",
          path: ""
        })
      })
  };

  //导出报表专用
  exportInfoProgressForReport = (param) => {
    ExportService.exportInfoProgressForReport(param)
      .then((res) => {
        this.setState({
          progressNum: res.data && res.data.progress ? parseInt(res.data.progress) : 0,
          path: "",
        });
        if (res.data.status === "S") {
          clearInterval(this.state.timer);
          this.setState({
            step: "success",
            path: res.data.path
          })
        } else if (res.data.status === "E") {
          clearInterval(this.state.timer);
          this.setState({
            step: "error",
            path: "",
            errorDetail: res.data.errorDetail
          })
        } else {
          clearInterval(this.state.timer);
          let that = this;
          this.state.timer = setInterval(function () {
            that.exportInfoProgressForReport(param);
          }, 2000)
        }
      })
      .catch((err) => {
        clearInterval(this.state.timer);
        this.setState({
          step: "error",
          path: ""
        })
      })
  };
  //自动下载
  downloadByPath = (path) => {
    window.open(this.state.path, '_blank');
  };


  //初始化组件
  setInitState = () => {
    clearInterval(this.state.timer);
    let step = "pending";
    let _mobile = this.encodeEmailOrMobile("mobile", this.props.user);
    let _email = this.encodeEmailOrMobile("email", this.props.user);
    let getCodeType = "mobile";
    if(_mobile === undefined){
      getCodeType = "email";
    }
    //如果需要安全验证
    if (this.props.codeCheck && this.props.company.exportSecurity) {
      step = "codeCheck";
      this.setState({
        codeCheckConfirming: false,
        isSended: false,
        getCodeType,
        visible: true,
        progressNum: 0,
        timeNumber: 0,
        path: "",
        _mobile,//手机加密
        _email,//邮箱加密
        step,
      })
    } else {
      //不需要安全验证，直接下载
      this.startDownload(step)
    }
  };
  startDownload = (step) => {
    this.setState({
      codeCheckConfirming: false,
      visible: true,
      progressNum: 0,
      path:  "",
      token: "",
      step,
    }, () => {
      this.exportInfo();
    })
  };
  //取消下载
  handleCancel = () => {
    clearInterval(this.state.timer);
    this.setState({
      isSended: false,
      visible: false,
      isCancel: true,
      token:""
    })
  };

  //重新下载
  reload = () => {
    clearInterval(this.state.timer);
    this.setState({
      visible: true,
      timeNumber: 0,
      step: "pending"
    }, () => {
      this.exportInfo();
    })
  };
  //关闭
  handleClose = () => {
    clearInterval(this.state.timer);
    this.setState({
      visible: false,
    })
  };
  //验证码 安全验证 ------start-------
  //加密邮箱或者手机
  encodeEmailOrMobile = (type, user) => {
    let t = "";
    if (type === "email") {
      if (user.email && user.email.length && user.email.length > 4 && user.email.match(/@/)) {
        t = user.email.slice(0, 2) + " **** @" + user.email.split("@")[1];
        return t;
      }else {
        return undefined;
      }
    } else {
      if (user.mobile && user.mobile.length && user.mobile.length > 4) {
        t = user.mobile.slice(0, 3) + " **** " + user.mobile.slice(user.mobile.length - 4, user.mobile.length)
        return t;
      }else {
        return undefined;
      }
    }
  };
  getCodeTypeChange = (val) => {
    this.setState({
      getCodeType: val,
      timeNumber: 0
    })
  };
  codeCheckGetCode = () => {
    let params = null;
    if (this.state.getCodeType === "email") {
      params = {
        login: this.props.user.email,
        type: this.state.getCodeType
      }
    } else {
      params = {
        login: this.props.user.mobile,
        type: this.state.getCodeType
      }
    }
    this.setState({
      isSended: true,
      timeNumber: 60
    });
    ExportService.getCode(params)
      .then(res => {
        clearInterval(codeTimer);
        codeTimer = setInterval(() => {
          let timeNumber = this.state.timeNumber;
          timeNumber--;
          if (timeNumber === 0) {
            clearInterval(codeTimer);
          }
          this.setState({
            timeNumber
          })
        }, 1000);
        message.success(messages('components.key447'/*发送成功*/))
      })
  };
  codeCheckConfirm = () => {
    this.setState({
      codeCheckConfirming: true
    });
    let params = null;
    if (this.state.getCodeType === "email") {
      params = {
        login: this.props.user.email,
        type: this.state.getCodeType,
        token: this.state.token,
      }
    } else {
      params = {
        login: this.props.user.mobile,
        type: this.state.getCodeType,
        token: this.state.token,
      }
    }
    ExportService.checkCode(params)
      .then(res => {
        this.setState({
          codeCheckConfirming: false
        });
        this.startDownload("pending")
      })
      .catch(()=>{
        this.setState({
          codeCheckConfirming: false
        })
      })
  };
  tokenChange = (e) => {
    this.setState({
      token: e.target.value
    })
  };
  codeCheckCancel = () => {
    this.handleCancel();
  };
  //验证码 安全验证 ------end-------

  //渲染过程
  renderContentByStep = (step) => {
    const {_mobile, _email, getCodeType, timeNumber,progressNum,isSended,token,codeCheckConfirming,
      errorDetail} = this.state;
    switch (step) {
      case "codeCheck": {
        return (
          <div className="step-code-check">
            <div className="title-wrap"> {messages('components.key448'/*安全验证*/)}
              <div className="title-desc-wrap">{messages('components.key449'/*为确保数据安全，请进行安全验证*/)}</div>
            </div>

            <div className="row">
              <div className="row-int-wrap">
                <InputGroup compact>
                  <Select key={getCodeType} style={{width: '30%'}} defaultValue={getCodeType}
                          onChange={this.getCodeTypeChange}>
                    {_mobile && <Option value="mobile">{messages('components.key450'/*手机*/)}</Option>}
                    { _email && <Option value="email">{messages('components.key451'/*邮箱*/)}</Option>}
                  </Select>
                  <Input style={{width: '70%'}}
                         disabled={true}
                         value={getCodeType === "mobile" ? _mobile : _email}/>
                </InputGroup>
              </div>
              <div className="row-btn-wrap">
                {!isSended && <Button
                  onClick={this.codeCheckGetCode}
                  type="primary"
                  disabled={timeNumber > 0}>
                  {messages('components.key452'/*验证码*/)} {timeNumber > 0 ? timeNumber : ""}
                </Button>}
                {isSended && <Button
                  onClick={this.codeCheckGetCode}
                  type="primary"
                  disabled={timeNumber > 0}>
                  {messages('components.key453'/*重新获取*/)} {timeNumber > 0 ? timeNumber : ""}
                </Button>}
              </div>
              <div className="clear"></div>
            </div>
            <div className="row">
              <Input placeholder={messages('components.key454'/*请输入验证码*/)}
                     value={token}
                     onChange={this.tokenChange}/>
            </div>

            <div className="btn-wrap">
              <Button type="primary"
                      disabled={!(token && token.length>0) || codeCheckConfirming}
                      onClick={this.codeCheckConfirm}> {messages('components.key455'/*确认*/)}
              </Button>
              &nbsp;&nbsp;&nbsp;
              <Button onClick={this.codeCheckCancel}> {messages('common.cancel')/*取消*/}
              </Button>
            </div>
          </div>
        )
        break
      }
      case "pending": {
        return (
          <div className="step-pending">
            <div className="title-wrap">
              <div>
                {messages('components.key456'/*数据加载中...*/)}
              </div>
            </div>
            <div className="progress-wrap">
              <Progress percent={progressNum} status="active"/>
            </div>
            <div className="loading-tip">
              <div>
                {messages('components.key457'/*请勿关闭或者离开当前页面，否则将导致下载失败*/)}
              </div>
            </div>
            <div className="btn-wrap">
              <Button type="primary"
                      onClick={this.handleCancel}>
                {messages('components.key458'/*取消下载*/)}
              </Button>
            </div>
          </div>
        )
        break
      }
      case "success": {
        return (
          <div className="step-success">
            <div className="title-wrap">
              <div>
                <Icon className="icon-success" type="check-circle"/>
                {messages('components.key459'/*加载成功，请点击下载*/)}
              </div>
            </div>
            <div className="progress-wrap">
              <Progress percent={progressNum} status="active"/>
            </div>
            <div className="btn-wrap">
              <Button type="primary" onClick={this.downloadByPath}>
                {messages('components.key460'/*下载*/)}
              </Button>
              &nbsp; &nbsp;&nbsp;
              <Button onClick={this.handleClose}>
                {messages('components.key461'/*关闭*/)}
              </Button>
            </div>
          </div>
        )
        break
      }
      case "error": {
        return (
          <div className="step-error">
            <div className="title-wrap">
              <div>
                <Icon className="icon-error" type="close-circle"/>
                {messages('components.key462'/*加载失败，请重试*/)}
              </div>
            </div>
            <div className="progress-wrap">
              <Progress percent={50} status="active"/>
            </div>

            <div className="loading-tip">
              <div>
                {errorDetail}
              </div>
            </div>

            <div className="btn-wrap">
              <Button type="primary"
                      onClick={this.reload}>
                {messages('components.key463'/*重新下载*/)}
              </Button>
              &nbsp; &nbsp;&nbsp;
              <Button type="primary"
                      onClick={this.handleClose}>
                {messages('components.key461'/*关闭*/)}
              </Button>
            </div>
          </div>
        )
        break
      }
    }
  }

  render() {
    const {exportTitle,type,disabled,btnType,style,btnSize,btnIcon} = this.props;
    const {visible,step} = this.state;
    return (
      <div className="export-modal-wrap" style={style}>
        {type === "btn" ?
          <Button type={btnType}
                  disabled={disabled}
                  icon={btnIcon}
                  size={btnSize}
                  onClick={this.setInitState}>
            {exportTitle}</Button> : type === 'expense' ? <div className="new-expense-apportion" onClick={this.setInitState}>{messages('my-account.key399')}</div> : <div style={{'color': disabled ? '#B5C0CE': ''}} onClick={!disabled && this.setInitState}>
            {exportTitle}</div>}

        <Modal
          width={500}
          maskClosable={false}
          closable={false}
          keyboard={false}
          className="export-modal-wrap-modal"
          title={null}
          destroyOnClose={true}
          visible={visible}
          footer={null}
          onCancel={this.handleCancel}
        >
          <div className="export-modal">
            {this.renderContentByStep(step)}
          </div>
        </Modal>
      </div>
    );
  }
}

ExportModal.propTypes = {
  btnSize: React.PropTypes.string, // 按钮大小
  btnIcon: React.PropTypes.string, // 按钮大小
  onConfirm: React.PropTypes.func,// 点击确认之后的回调：返回结果
  onCancel: React.PropTypes.func,//点击取消的时候
  exportTitle: React.PropTypes.any,//导出按钮上的文本
  exportType: React.PropTypes.any,//导出类型
  exportCommand: React.PropTypes.any,//导出命令，请查看本组件的文档  readme.
  exportCondition: React.PropTypes.any,//条件
  type: React.PropTypes.any,//按钮类型，btn,text
  btnType: React.PropTypes.any,//按钮类型，btn,text
  disabled: React.PropTypes.bool,//按钮是否禁用
  codeCheck: React.PropTypes.bool,//验证码校验，为true就要校验,
  style: React.PropTypes.object
};

ExportModal.contextTypes = {
  router: React.PropTypes.object
};
ExportModal.defaultProps = {
  btnSize: 'middle',
  btnIcon: null,
  type: "text",
  disabled: false,
  codeCheck: false
};

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
    user: state.login.user,
    tenantMode: state.main.tenantMode,
    company: state.login.company,
  }
}

const WrappedExportModal = Form.create()(ExportModal);

export default connect(mapStateToProps)(WrappedExportModal);



